import {
  CHANGE_INPUT_VALUE,
  ADD_TODO_ITEM,
  DELETE_TODO_ITEM,
  INIT_LIST_ACTION,
  GET_INIT_LIST,
} from "./actionTypes";
import axios from "axios";

export const getInputChangeAction = (value, index) => {
  return {
    type: CHANGE_INPUT_VALUE,
    value,
    index,
  };
};

export const getAddItemAction = (value) => {
  return {
    type: ADD_TODO_ITEM,
    value,
  };
};

export const getDeleteItemAction = (index) => {
  return {
    type: DELETE_TODO_ITEM,
    index,
  };
};

export const initListAction = (data) => {
  return {
    type: INIT_LIST_ACTION,
    data,
  };
};

export const getTodoList = () => {
  return async (dispatch) => {
    const {
      data: {
        result: { list },
      },
    } = await axios.get("/rate/query?key=55df4c26d71d74689377021a3b2a6fcf");
    const dataList = list.map((item) => {
      return {
        item: item[0],
      };
    });
    const arr = [];
    for (let val of dataList) {
      if (val.item) {
        arr.push(val.item);
      }
    }
    const action = initListAction(arr);
    dispatch(action);
  };
};

export const deleteItem = (id, index) => {
  return async (dispatch) => {
    const {
      msg: { code },
    } = await axios.delete("/rate/query?key=55df4c26d71d74689377021a3b2a6fcf");
    if (code === 200) {
      const action = getDeleteItemAction(index);
      dispatch(action);
    }
  };
};

export const addItem = (value) => {
  return async (dispatch) => {
    let tid = new Date().getTime();
    const {
      msg: { code },
    } = await axios.post("/rate/query?key=55df4c26d71d74689377021a3b2a6fcf", {
      data: { id: tid, value: value },
    });
    if (code === 200) {
      const action = getAddItemAction({ id: tid, value: value });
      dispatch(action);
    }
  };
};

export const changeItem = (value, index, id) => {
  return async (dispatch) => {
    const {
      mag: { code },
    } = await axios.post("/rate/query?key=55df4c26d71d74689377021a3b2a6fcf", {
      data: {
        id: id,
        value: value,
      },
    });
    if (code === 200) {
      const action = getInputChangeAction(value, index);
      dispatch(action);
    }
  };
};
